import time
from django.shortcuts import render
from django.conf import settings
import os

from contents.models import ContentCategory
from .utils import get_categories



def generate_static_index_html():
    print('%s: generate_static_index_html' % time.ctime())
    contents = {}
    # 查出所有的广告类别(查询集）
    content_qs = ContentCategory.objects.all()
    for content_cat in content_qs:
        contents[content_cat.key] = content_cat.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories': get_categories(),
        'contents': contents
    }
    response = render(None, 'index.html', context)
    html_str = response.content.decode()
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path,'w',encoding='utf-8') as w:
        w.write(html_str)